#!/bin/bash -e

# Show help if no arguments provided
if [ $# -eq 0 ]; then
    echo "Usage: run-script <script-path>"
    echo "Example: run-script Application/Script/HelloWorldToAllUsers.hs"
    exit 1
fi

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
TASK_PATH="$*"

# Validate that TASK_PATH is not empty
if [ -z "$TASK_PATH" ]; then
    echo "Error: Script path cannot be empty"
    exit 1
fi

# Extract module name safely
TASK_MODULE="${TASK_PATH##*/}"
TASK_MODULE="${TASK_MODULE%.*}"

# Validate module name
if [ -z "$TASK_MODULE" ]; then
    echo "Error: Could not extract module name from path: $TASK_PATH"
    exit 1
fi


# Ensure we are in an app dir
if [ ! -f Main.hs ]; then
    echo "You have to be in a project directory to run the script"
    exit 1
fi

if [ -z "$IHP" ]; then
    echo "Error: Could not locate IHP framework directory"
    exit 1
fi

GHCI_SCRIPT="$(mktemp)"
trap "rm $GHCI_SCRIPT" EXIT

echo ":set prompt \"\"" >> "$GHCI_SCRIPT"

# Inline applicationGhciConfig but exclude :set prompt and :l Main.hs
grep -vE '^[[:space:]]*:l[[:space:]]*Main\.hs$|^[[:space:]]*:set[[:space:]]+prompt' \
    "$IHP/lib/IHP/applicationGhciConfig" >> "$GHCI_SCRIPT"

# Add a line break for safety
echo "" >> "$GHCI_SCRIPT"

# Load the actual script
if [ -d IHP ]; then
    echo ":l IHP/IHP/ScriptSupport.hs $TASK_PATH" >> "$GHCI_SCRIPT"
else
    echo "import IHP.ScriptSupport" >> "$GHCI_SCRIPT"
fi

echo "import IHP.ScriptSupport" >> "$GHCI_SCRIPT"
echo ":l Config/Config.hs Application/Script/$TASK_MODULE.hs" >> "$GHCI_SCRIPT"
echo "import qualified Application.Script.$TASK_MODULE as Script" >> "$GHCI_SCRIPT"
echo "IHP.ScriptSupport.runScript config Script.run" >> "$GHCI_SCRIPT"
echo ":quit" >> "$GHCI_SCRIPT"

ghci -ignore-dot-ghci -package-env - -threaded -fomit-interface-pragmas +RTS -A128m -RTS < "$GHCI_SCRIPT"